<template>
    <div class="clearingDeteleCount">
        <SearchBar class="form" @onSearch="handleSearch" @childFn="resetForm">
            <SearchBarItem label="对账日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="createDatePicker"
                    split-panels
                    transfer
                    placeholder="起始时间"
                    @on-change="createTime"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="是否有差异未处理：" :labelLg="8">
                <Select
                    v-model="dataModule.isError"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in stateList"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="商户号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.subMchId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="付款账户名：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.payAcctName"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="收款账户名：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.colAcctName"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
        </SearchBar>
        <RemoteTable
            ref="remoteTable"
            :namespace="namespace"
            :columns="columns"
            :showPageInfo="false"
            :isFixedHeader="true"
            @onSelectionChange="getListChecked"
        >
          <template #extra>
            <Authc permissions="trade:settlement:cmb">
              <Button type="primary" @click="exportExcel">导出</Button>
            </Authc>
          </template>
        </RemoteTable>
        <br />
        <Row>
            <Col span="12" offset="11">
                <Button type="primary" @click="loadMore" :disabled="isDisabledloadBtn" :isClear="isClear">加载更多</Button>
            </Col>
        </Row>
    </div>
</template>
<script>
import {
    Button,
    Input,
    Modal,
    Message,
    DatePicker,
    Select,
    Option,
    Row,
    Col
} from "view-design";
import util from "@/utils/util";
import RemoteTable from "@/components/RemoteTable";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../../Module/clearingDeteleCountModule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";

export default {
    name: "clearingDetele",
    components: {
        RemoteTable,
        SearchBar,
        SearchBarItem: SearchBar.SearchBarItem,
        Authc,
        Action,
        Button,
        Input,
        Modal,
        Message,
        DatePicker,
        Select,
        Option,
        Row,
        Col
    },
    props: {
        clearingDate: Array
    },
    data() {
        return {
            namespace: namespace,
            isClear: true,
            loading: true,
            modal1: false,
            isDisabledloadBtn: false, /** 控制加载更多按钮 **/
            currentPage: 1, /** 用来控制加载更新 **/
            exportData: [], /** 导出数据 **/
            stateList: [
                {
                    key: "1",
                    value: "是"
                },
                {
                    key: "0",
                    value: "否"
                }
            ],
            dataModule: {}, //查询条件
            columns: [
                {
                    title: "平台清分汇总",
                    align: "center",
                    children: [
                        {
                            type: "selection",
                            align: "center",
                            minWidth: 55
                        },
                        {
                            title: "序号",
                            type: "index",
                            align: "center",
                            minWidth: 80
                        },
                        {
                            title: "清分日期",
                            key: 'clearDate',
                            align: "",
                            minWidth: 120
                        },
                        {
                            title: "商户号",
                            key: "subMchId",
                            align: "center",
                            minWidth: 160
                        },
                        {
                            title: "付款账户名",
                            key: "payAcctName",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "付款账号",
                            key: "payAcct",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "收款账户名",
                            key: "colAcctName",
                            align: "center",
                            minWidth: 190
                        },
                        {
                            title: "收款账号",
                            key: "colAcct",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "清分金额(元)",
                            key: "clearAmountCount",
                            align: "center",
                            minWidth: 140,
                            render: function(h, data){
                                let item = data.row.clearAmountCount / 100;
                                 return h('span', util.toMoney(item));
                            }
                        },
                        {
                            title: "清分记账数",
                            key: "subOrderCount",
                            align: "center",
                            minWidth: 100
                        }
                    ]
                },
                {
                    title: "银行清分汇总",
                    align: "center",
                    children: [
                        {
                            title: "清分执行时间",
                            key: "bankClearDate",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "清分金额(元)",
                            key: 'bankClearAmount',
                            align: "center",
                            minWidth: 140,
                            render: function(h, data){
                                let item = data.row.bankClearAmount / 100;
                                 return h('span', util.toMoney(item));
                            }
                        },
                        {
                            title: "清分记账数",
                            key: 'bankClearAmountCount',
                            align: "center",
                            minWidth: 100
                        }
                    ]
                },
                {
                    title: "差异汇总",
                    key: "gender",
                    align: "center",
                    children: [
                        {
                            title: "对账日期",
                            key: "billDate",
                            align: "center",
                            minWidth: 120,
                            render: (h, params) => {
                                let item = params.row.billDate ? params.row.billDate.slice(0, 10) : params.row.billDate;
                                return h('span', item)
                            }
                        },
                        {
                            title: "差异",
                            key: "diffClearAmountCount",
                            align: "center",
                            minWidth: 100,
                            render: (h, params) => {
                                return h('span', params.row.diffClearAmountCount / 100)
                            }
                        },
                        {
                            title: "差异笔数",
                            key: "diffOrderCount",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "已处理笔数",
                            key: "processedCount",
                            align: "center",
                            minWidth: 110
                        },
                        {
                            title: "操作",
                            key: "action",
                            align: "center",
                            permissions: ["trade:settlement:cmb"],
                            minWidth: 200,
                            render: function(h, data) {
                                return h(Action, {
                                    props: {
                                        row: data.row,
                                        isShowBtn: data.row.diffOrderCount === 0 ? false : true
                                    }
                                });
                            }
                        }
                    ]
                }
            ]
        };
    },
    created() {
        /**
         * 如果 url 没有带参数，就重置请求参数
         * 有就添加到 vuex
        * **/
       let clearDate = util.getUrlParam('clearDate');
        if (clearDate) {
            this.$store.commit(`${namespace}/setQuery`, {
                startDate: clearDate,
                endDate: clearDate
            });
        } else {
            this.$store.commit(`${namespace}/reviseQuery`);
        }
    },
    mounted() {

    },
    methods: {
        exportExcel() {

            if( this.exportData.length == 0 ) {
                this.$Message.error({
                    content: '请选择导出的数据'
                });
                return;
            } else {
                this.exportData.forEach(e => {
                    // if (e.clearAmountCount || e.bankClearAmount) {
                        // e.clearAmountCount = e.clearAmountCount / 100
                        // e.bankClearAmount = e.bankClearAmount / 100

                        e.clearDate = e.clearDate || ''
                        e.subMchId = e.subMchId || ''
                        e.payAcctName = e.payAcctName || ''
                        e.payAcct = e.payAcct || ''
                        e.colAcctName = e.colAcctName || ''
                        e.colAcct = e.colAcct || ''
                        e.clearAmountCount = (e.clearAmountCount / 100) || '\t0'
                        e.subOrderCount = e.subOrderCount || '\t0'
                        e.bankClearDate = e.bankClearDate || ''
                        e.bankClearAmount = (e.bankClearAmount / 100) || '\t0'
                        e.bankClearAmountCount = e.bankClearAmountCount || '\t0'
                        e.billDate = e.billDate || ''
                        e.diffClearAmountCount = e.diffClearAmountCount || '\t0'
                        e.diffSubOrderCount = e.diffSubOrderCount || '\t0'
                        e.diffOrderCount = e.diffOrderCount || '\t0'
                    // }
                })
            }

            /** 多表头处理 **/
            let exportColumn = this.handleMultiTableHeader(this.columns, false);

            /** 复制一份表头 **/
            let columnOne = {};
            exportColumn.forEach(item => {
                columnOne[item.key] = item.title;
            });

            /** 自定义导出表格第一行的表头，逗号表示隔开几个单元格 **/
            let tableTitle = {
                clearDate: `${this.columns[0].title},,,,,,,,${this.columns[1].title},,,${this.columns[2].title}`,
                subMchId: '',
                payAcctName: '',
                payAcct: '',
                colAcctName: '',
                colAcct: '',
                clearAmountCount: '',
                subOrderCount: '',
                bankClearDate: '',
                bankClearAmount: '',
                bankClearAmountCount: '',
                billDate: '',
                diffClearAmountCount: '',
                diffSubOrderCount: '',
                diffOrderCount: '',
            }
            /** 复制一份导出数据 **/
            let copyTableData = JSON.parse(JSON.stringify(this.exportData));

            /** 把自定义的表头和复制出来的表头，添加到导出数据前面 **/
           copyTableData.unshift(tableTitle, columnOne);

            let tables = this.$refs.remoteTable.getTables();
            tables.exportCsv({
                filename: '清分汇总对账',
                columns: exportColumn,
                data: copyTableData.map(item => {
                    return {
                        clearDate: `\t${item.clearDate}`,
                        subMchId: `\t${item.subMchId}`,
                        payAcctName: `\t${ item.payAcctName }`,
                        payAcct: `\t${item.payAcct}`,
                        colAcctName: `\t${ item.colAcctName }`,
                        colAcct: `\t${item.colAcct}`,
                        clearAmountCount: `\t${item.clearAmountCount}`,
                        subOrderCount: `\t${item.subOrderCount}`,
                        bankClearDate: `\t${item.bankClearDate}`,
                        bankClearAmount: `\t${item.bankClearAmount}`,
                        bankClearAmountCount: `\t${item.bankClearAmountCount}`,
                        billDate: `\t${item.billDate}`,
                        diffClearAmountCount: `\t${item.diffClearAmountCount}`,
                        diffSubOrderCount: `\t${item.diffSubOrderCount}`,
                        diffOrderCount: `\t${item.diffOrderCount}`,
                    }
                }),
                noHeader: true
            });
        },
        /** 搜索 **/
        handleSearch() {
            this.currentPage = 1;
            let obj = {
                currentPage: 1,
                pageSize: 50
            };
            if ( this.clearingDate.length != 0 ) {
                obj.startDate = this.clearingDate[0];
                obj.endDate = this.clearingDate[1];
            }
            this.$store.dispatch(`${namespace}/query`, {...this.dataModule, ...obj});
        },
        /** 加载更多 **/
        async loadMore() {
            console.log(this.clearingDate, '---------clearingDate')
             let dataList = this.$store.state[namespace].pageInfo.list;

                // console.log(dataList.length, this.exportData.length)
            for (let i = 0; i < dataList.length; i++) {
                for (let j = 0; j < this.exportData.length; j++) {
                    if (this.exportData[j].subOrderId == dataList[i].subOrderId) {
                        dataList[i]._checked = true;
                    }
                }
            }
            let time
            if (this.clearingDate.length) {
                time = {
                    startDate: this.clearingDate[0],
                    endDate: this.clearingDate[1]
                }
            } else {
                time = {
                    startDate: util.fun_date(-7),
                    endDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()
                }
            }
            try {
                this.isDisabledloadBtn = true; /** 每次请求都禁止按钮点击 **/
                let obj = {
                    currentPage: ++this.currentPage,
                    pageSize: 50,
                };
                /** 因为不是翻页，所以重新写了一个列表的请求 **/
                let res = await this.$store.dispatch(`${namespace}/getMoreList`, { ...time, ...this.dataModule, ...obj });
                let listData = res.data.data.list;
                if (listData.length != 0) {
                    /** 拿到数据，就拼接到 vuex 里面 **/
                    this.$store.commit(`${namespace}/pushDataToList`, listData);
                } else {
                    --this.currentPage;
                    this.$Message.info({
                        content: '没有更多数据了！'
                    });
                }
                this.isDisabledloadBtn = false;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 获取选中的数据 **/
        getListChecked(data){
            this.exportData = data;
        },
        /** cy 处理多表头导出问题 **/
        handleMultiTableHeader (columns) {
            return columns.map(res => {
                if (res.hasOwnProperty('children')) {
                    /** 通过 key 过滤掉 复选框和序号还有操作栏 **/
                    return res.children.filter(item => {
                        return item.key;
                    })
                } else {
                    return res;
                }
            }).flat();
        },
        /** 清空事件 **/
        resetForm() {
            this.$set(this.dataModule, 'isError', '');
            this.$set(this.dataModule, 'subMchId', '');
            this.$set(this.dataModule, 'payAcctName', '');
            this.$set(this.dataModule, 'colAcctName', '');
            // 清空时间选择
            this.$refs["createDatePicker"].handleClear();
        },
        /** 对账日期 **/
        createTime(date, type) {
            this.dataModule.billDateBegin = date ? date[0] : "";
            this.dataModule.billDateEnd = date ? date[1] : "";
        },
        goToDetails() {
            this.$router.push({
                path: "/settlement/admin/SettlementCollectCenter/ClearingDeteleForm",
                query: { id: "111111111" }
            });
        }
    },
};
</script>

<style lang="less" scoped>
    .clearingDeteleCount {

    }
</style>
